<template>
  <div class="container">
    <div class="form-content">
      <a-form layout="inline">
        <a-form-item label="时间范围">
          <a-range-picker v-model:value="data" />
        </a-form-item>
        <a-form-item label="邀约状态">
          <a-select
            allowClear
            v-model:value="invitationStatus"
            style="width: 200px"
            placeholder="请选择职位标签"
            :options="statusList"
            @change="handleChange"
          ></a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" class="search-botton" @click="search">搜索</a-button>
          <a-button @click="reset">重置</a-button>
        </a-form-item>
      </a-form>
      <div>
        <a-radio-group v-model:value="store.invitationFlag" style="margin-right: 12px">
          <a-radio-button :value="true">我的邀约</a-radio-button>
          <a-radio-button :value="false">所有邀约</a-radio-button>
        </a-radio-group>
      </div>
    </div>
    <div class="echarts-content">
      <div class="chart-container">
        <e-charts class="chart" :option="assessmentOption" />
      </div>
      <div class="chart-container">
        <e-charts class="chart" :option="interviewOption" />
      </div>
    </div>
    <div class="table-content">
      <span style="display: inline-block; padding-bottom: 5px; font-size: 20px; font-weight: 600"
        >面试列表</span
      >
      <a-table
        class="table"
        :columns="columns"
        :data-source="store.invitationList"
        :loading="store.loading"
        :scroll="{ x: 1500, y: 320 }"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <div v-if="column.key === 'operation'">
            <a-popconfirm
              title="确认通过邀约?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handlePass(record)"
            >
              <a-button type="link" size="small">通过</a-button>
            </a-popconfirm>

            <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              title="确认撤回邀约?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleWithdraw(record)"
            >
              <a-button type="link" size="small">撤回邀约</a-button>
            </a-popconfirm>
          </div>
        </template>
      </a-table>
    </div>
    <div class="page-content">
      <a-pagination
        v-if="store.total > 0"
        v-model:page-size="store.pageSize"
        :page-size-options="['10', '20', '50']"
        :total="store.total"
        :show-total="total => `共 ${total} 条`"
        show-size-changer
        @change="onPageChange"
      >
      </a-pagination>
    </div>
  </div>
  <a-modal v-model:open="modalOpen" title="编辑邀约" @ok="handleOk">
    <a-form>
      <a-form-item label="职位名称">
        <a-select
          v-model:value="positionName"
          :options="positionList"
          placeholder="请选择职位名称"
        ></a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useInvitationStore } from '@/stores/invitationStore'
import { useUserStore } from '@/stores/userStore'
import { message } from 'ant-design-vue'
import server from '@/api/index'
import dayjs from 'dayjs'

const store = useInvitationStore()
const userStore = useUserStore()

const modalOpen = ref(false)

const columns = [
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    width: 100,
    fixed: 'left',
  },
  {
    title: 'HRID',
    dataIndex: 'hrId',
    key: 'hrId',
    width: 150,
  },
  {
    title: 'HR名',
    dataIndex: 'hrName',
    key: 'hrName',
    width: 150,
  },
  {
    title: '职位ID',
    dataIndex: 'positionId',
    key: 'positionId',
    width: 150,
  },
  {
    title: '职位名称',
    dataIndex: 'positionName',
    key: 'positionName',
    width: 150,
  },
  {
    title: '公司ID',
    dataIndex: 'companyId',
    key: 'companyId',
    width: 150,
  },
  {
    title: '公司名称',
    dataIndex: 'companyName',
    key: 'companyName',
    width: 150,
  },

  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 150,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 200,
    fixed: 'right',
  },
]
const statusList = [
  {
    label: '已发起',
    value: 1,
  },
  {
    label: '已接受',
    value: 2,
  },
  {
    label: '已通过',
    value: 3,
  },
  {
    label: '已确认',
    value: 4,
  },
  {
    label: '已拒绝',
    value: 5,
  },
]

const onPageChange = async (page, pageSize) => {
  store.page = page
  store.pageSize = pageSize
  if (store.invitationFlag.value) {
    getMyInvitationList()
  } else {
    getAllInvitationList()
  }
}
const status = ref('')
const positionName = ref()
const positionList = ref()
const data = ref([])
const invitationStatus = ref([])
const search = async () => {
  if (store.invitationFlag) {
    const res = await server.getlistMyInvitationVOByPage({
      startDate: data.value?.[0]?.format('YYYY/MM/DD HH:mm:ss'),
      endDate: data.value?.[1]?.format('YYYY/MM/DD HH:mm:ss'),
      status: invitationStatus.value,
      current: store.page,
      pageSize: store.pageSize,
    })
    if (res.data.code === 0) {
      store.total = res.data.data.total
      store.invitationList = res.data.data.records
      message.success(res.data.message)
    } else {
      message.error(res.data.message)
    }
  } else {
    const res = await server.getlistInvitationVOByPage({
      startDate: data.value?.[0]?.format('YYYY/MM/DD HH:mm:ss'),
      endDate: data.value?.[1]?.format('YYYY/MM/DD HH:mm:ss'),
      status: invitationStatus.value,
      current: store.page,
      pageSize: store.pageSize,
    })
    if (res.data.code === 0) {
      store.total = res.data.data.total
      store.invitationList = res.data.data.records
      message.success(res.data.message)
    } else {
      message.error(res.data.message)
    }
  }
}
const reset = () => {
  invitationStatus.value = []
  data.value = []
  if (store.invitationFlag) {
    getMyInvitationList()
  } else {
    getAllInvitationList()
  }
}
const handlePass = async item => {
  try {
    const res = await server.editInvitation({
      hrId: userStore.userAccount,
      hrName: userStore.userTureName,
      id: item.id,
      positionId: item.positionId,
      status: 3,
    })
    if (res.data.code === 0) {
      if (store.invitationFlag) {
        getInvitationList(positionId.value)
      } else {
        getAllInvitationList()
      }
    } else {
      message.warning(res.data.message)
    }
  } catch (e) {
    message.error(e)
  }
}
const editItem = ref()
const handleEdit = item => {
  editItem.value = item
  modalOpen.value = true
  positionName.value = item.positionName
  getMyCompanyPositionList()
  // 调接口获取列表数据
}
const handleOk = async () => {
  try {
    const res = await server.updateInvitation({
      positionName: positionName.value.slice(0, positionName.value.indexOf('$')),
      positionId: positionName.value.slice(positionName.value.indexOf('$') + 1),
      hrId: editItem.value.hrId,
      hrName: editItem.value.hrName,
      companyId: editItem.value.companyId,
      companyName: editItem.value.companyName,
      id: editItem.value.id,
    })
    if (res.data.code === 0) {
      message.success(res.data.message)
      modalOpen.value = false
      getMyInvitationList()
    } else {
      message.error(res.data.message)
    }
  } catch (e) {
    message.error(e)
  }
}
const handleWithdraw = async item => {
  try {
    const res = await server.editInvitation({
      hrId: userStore.userAccount,
      hrName: userStore.userTureName,
      id: item.id,
      positionId: item.positionId,
      status: 5,
    })
    if (res.data.code === 0) {
      if (store.invitationFlag) {
        if (store.invitationFlag) {
          getInvitationList(positionId.value)
        } else {
          getAllInvitationList()
        }
      } else {
        getAllInvitationList()
      }
    } else {
      message.warning(res.data.message)
    }
  } catch (e) {
    message.error(e)
  }
}
watch(
  () => store.invitationFlag,
  val => {
    if (val) {
      getMyInvitationList()
      // 获取个人数据接口
    } else {
      getAllInvitationList()
      // 获取所有数据
    }
  },
)

const getMyInvitationList = async () => {
  try {
    const res = await server.getlistMyInvitationVOByPage({
      hrId: userStore.userAccount,
      current: store.page,
      pageSize: store.pageSize,
    })
    if (res.data.code === 0) {
      store.invitationList = res.data.data.records
      store.total = res.data.data.total
      message.success(res.data.message)
      store.invitationList.forEach(item => {
        item.createTime = dayjs(res.data.data.records.createTime).format('YYYY/MM/DD')
        switch (item.status) {
          case 1:
            item.status = '已发起'
            break
          case 2:
            item.status = '已接受'
            break
          case 3:
            item.status = '已通过'
            break
          case 4:
            item.status = '已确认'
            break
          case 5:
            item.status = '已拒绝'
            break
        }
      })
      interviewOption.value = {
        title: {
          text: '笔试情况',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: [
          {
            name: '面试状态',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 0, name: '未笔试' },
              { value: 0, name: '笔试中' },
              { value: 0, name: '笔试完成' },
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      }
      assessmentOption.value = {
        title: {
          text: '测评情况',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: [
          {
            name: '测评状态',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 0, name: '已发起' },
              { value: 0, name: '测评中' },
              { value: 0, name: '未测评' },
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      }
    } else {
      message.error(`获取邀约列表失败: ${res.data.message}`)
    }
  } catch (e) {
    console.log(e)
    message.error(`获取邀约列表时发生错误: ${e.message}`)
  }
}
const getInvitationList = async positionId => {
  try {
    const res = await server.getlistMyInvitationVOByPage({
      hrId: userStore.userAccount,
      current: store.page,
      pageSize: store.pageSize,
      positionId,
    })
    if (res.data.code === 0) {
      store.invitationList = res.data.data.records
      store.total = res.data.data.total
      message.success(res.data.message)
      store.invitationList.forEach(item => {
        item.createTime = dayjs(res.data.data.records.createTime).format('YYYY/MM/DD')
        switch (item.status) {
          case 1:
            item.status = '已发起'
            break
          case 2:
            item.status = '已接受'
            break
          case 3:
            item.status = '已通过'
            break
          case 4:
            item.status = '已确认'
            break
          case 5:
            item.status = '已拒绝'
            break
        }
      })
    } else {
      message.error(`获取邀约列表失败: ${res.data.message}`)
    }
  } catch (e) {
    console.log(e)
    message.error(`获取邀约列表时发生错误: ${e.message}`)
  }
}
const getAllInvitationList = async () => {
  try {
    const res = await server.getlistInvitationVOByPage({
      current: store.page,
      pageSize: store.pageSize,
    })
    if (res.data.code === 0) {
      store.invitationList = res.data.data.records
      store.total = res.data.data.total
      message.success(res.data.message)
      store.invitationList.forEach(item => {
        item.createTime = dayjs(res.data.data.records.createTime).format('YYYY/MM/DD')
        switch (item.status) {
          case 1:
            item.status = '已发起'
            break
          case 2:
            item.status = '已接受'
            break
          case 3:
            item.status = '已通过'
            break
          case 4:
            item.status = '已确认'
            break
          case 5:
            item.status = '已拒绝'
            break
        }
      })
    } else {
      message.error(`获取邀约列表失败: ${res.data.message}`)
    }
  } catch (e) {
    message.error(`获取邀约列表时发生错误: ${e.message}`)
  }
}
// 面试情况饼图数据
const interviewOption = ref({})

// 测评情况饼图数据
const assessmentOption = ref({})

const getMyCompanyPositionList = async () => {
  const res = await server.getMyCompanyPositionList(userStore.userAccount)
  positionList.value = res.data.data.map(item => {
    return {
      label: item.title,
      value: item.title + '$' + item.positionId,
    }
  })
}

// 测评
const testData = ref([])
const examData = ref([])
const getTestRatio = async () => {
  const res = await server.testRatio(positionId.value)
  if (res.data.data.length > 0) {
    res.data.data.forEach(item => {
      if (item.status === 1) {
        testData.value.push({
          value: item.count,
          name: '已发起',
        })
      }
      if (item.status === 2) {
        testData.value.push({
          value: item.count,
          name: '测评中',
        })
      }
      if (item.status === 3) {
        testData.value.push({
          value: item.count,
          name: '已完成',
        })
      }
    })
    assessmentOption.value = {
      title: {
        text: '测评情况',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
      },
      series: [
        {
          name: '测评状态',
          type: 'pie',
          radius: '50%',
          data: testData.value,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    }
  } else {
    assessmentOption.value = {
      title: {
        text: '测评情况',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
      },
      series: [
        {
          name: '测评状态',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 0, name: '已发起' },
            { value: 0, name: '测评中' },
            { value: 0, name: '未测评' },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    }
  }
}

// 笔试
const getExamRatio = async () => {
  const res = await server.examRatio(positionId.value)
  if (res.data.data.length > 0) {
    res.data.data.forEach(item => {
      if (item.status === 4) {
        examData.value.push({
          value: item.count,
          name: '笔试中',
        })
      }
      if (item.status === 5) {
        examData.value.push({
          value: item.count,
          name: '已完成',
        })
      }
      let temp =''
      if (item.status === 1) {
        temp += item.count
      }
      if (item.status === 2) {
        temp += item.count
      }
      if (item.status === 3) {
        temp += item.count
      }
      examData.value.push({
        value: temp,
        name: '未笔试',
      })
    })
    interviewOption.value = {
      title: {
        text: '笔试情况',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
      },
      series: [
        {
          name: '面试状态',
          type: 'pie',
          radius: '50%',
          data: examData.value,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    }
  } else {
    interviewOption.value = {
      title: {
        text: '笔试情况',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
      },
      series: [
        {
          name: '面试状态',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 0, name: '未笔试' },
            { value: 0, name: '笔试中' },
            { value: 0, name: '笔试完成' },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    }
  }
}

const positionId = ref('')
onMounted(() => {
  if (!store.positionId) {
    getMyInvitationList()
  } else {
    positionId.value = store.positionId
    getInvitationList(positionId.value)
    getTestRatio()
    getExamRatio()
    store.positionId = null
  }
})
onUnmounted(() => {
  positionId.value = null
})
</script>

<style lang="scss" scoped>
.container {
  // display: flex;
  width: 100%;
  height: 100%;
  background-color: #fff;

  .form-content {
    display: flex;
    justify-content: space-between;
    padding: 20px 20px 0;

    .search-botton {
      margin-right: 10px;
    }
  }

  .table-content {
    padding: 15px;
  }

  .page-content {
    display: flex;
    justify-content: flex-end;
    padding-right: 15px;
  }

  .echarts-content {
    display: flex;
    justify-content: space-around;
    padding-top: 10px;
  }

  .chart-container {
    width: 40%;
  }

  .chart {
    width: 100%;
    height: 300px;
  }
}
</style>
